package com.itheima.reggie.commen;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${upload.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        UUID uuid = UUID.randomUUID();
        String filename = uuid + suffix;
        //判断文件夹是否存在，不存在则创建
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //将文件存储到指定的位置
        try {
            file.transferTo(new File(path + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //上传成功，返回文件名
        return R.success(filename);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            FileInputStream fis = new FileInputStream(new File(path + name));
            ServletOutputStream os = response.getOutputStream();
            response.setContentType("image/jpeg");
//            IOUtils.copy(fis,os);
            int len;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes,0,len);
            }
            os.flush();
            os.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
